package com.t4.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.t4.auth.mapper.SysRoleMapper;
import com.t4.auth.mapper.SysUserRoleMapper;
import com.t4.auth.service.SysRoleService;
import com.t4.model.system.SysRole;
import com.t4.model.system.SysUserRole;
import com.t4.vo.system.AssignRoleVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public HashMap<String, Object> toAssign(Long userId) {
        // 获取所有角色
        List<SysRole> allRolesList = this.list();

        // 获取用户拥有的角色id
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId).select(SysUserRole::getRoleId);
        List<SysUserRole> existUserRoleList = sysUserRoleMapper.selectList(queryWrapper);

        List<Long> existRoleIdList = new ArrayList<>();
        existUserRoleList.forEach(i -> {
            existRoleIdList.add(i.getRoleId());
        });

        // 将拥有的角色id转成角色列表
        List<SysRole> assginRoleList = new ArrayList<>();
        allRolesList.forEach(i -> {
            if(existRoleIdList.contains(i.getId())){
                assginRoleList.add(i);
            }
        });

        HashMap<String, Object> map = new HashMap<>();
        map.put("allRolesList", allRolesList);
        map.put("assginRoleList", assginRoleList);
        return map;
    }

    @Transactional // 该方法包括先删除后添加，如果添加方法失败了，应该回退删除
    @Override
    public void doAssign(AssignRoleVo assginRoleVo) {
        // 用户id
        Long userId = assginRoleVo.getUserId();
        // 角色id列表
        List<Long> roleIdList = assginRoleVo.getRoleIdList();

        // 删除用户id原有的角色
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        sysUserRoleMapper.delete(queryWrapper);

        // 封装新的SysUserRole，并添加到数据库
        roleIdList.forEach(i -> {
            if(!StringUtils.isEmpty(i)) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(i);
                sysUserRoleMapper.insert(sysUserRole);
            }
        });

    }
}
